
def cut_history(history, length=128000):
    # keep the last 128k characters of the history
    cutted_history = []
    total_length = 0
    for message in history[::-1]:
        if total_length + len(message['content']) < length:
            cutted_history.append(message)
            total_length += len(message)
        else:
            break
    
    return cutted_history[::-1]